"""Word 文档生成模块"""
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from typing import Dict, List


class DocGenerator:
    """Word 文档生成器"""
    
    def __init__(self, database_name: str):
        """
        初始化文档生成器
        
        Args:
            database_name: 数据库名称
        """
        self.database_name = database_name
        self.doc = Document()
    
    def generate(self, schema: Dict[str, List[Dict]], output_path: str):
        """
        生成 Word 文档
        
        Args:
            schema: Schema 信息字典，key 为表名，value 为字段信息列表
            output_path: 输出文件路径
        """
        # 添加标题
        self._add_title()
        
        # 为每个表添加章节
        for table_name in sorted(schema.keys()):
            self._add_table_section(table_name, schema[table_name])
        
        # 保存文档
        self.doc.save(output_path)
    
    def _add_title(self):
        """添加文档标题"""
        title = self.doc.add_heading(f'{self.database_name} 数据库表结构说明', 0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        # 添加空行
        self.doc.add_paragraph()
    
    def _add_table_section(self, table_name: str, columns: List[Dict]):
        """
        添加表的章节
        
        Args:
            table_name: 表名
            columns: 字段信息列表
        """
        # 添加表名标题
        heading = self.doc.add_heading(f'表名：{table_name}', level=1)
        
        # 添加字段表格
        table = self.doc.add_table(rows=1, cols=6)
        table.style = 'Light Grid Accent 1'
        
        # 设置表头
        header_cells = table.rows[0].cells
        headers = ['字段名', '类型', '长度', '允许空', '默认值', '备注']
        
        for i, header in enumerate(headers):
            cell = header_cells[i]
            cell.text = header
            # 设置表头格式
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
                    run.font.size = Pt(10)
        
        # 添加数据行
        for col in columns:
            row_cells = table.add_row().cells
            row_cells[0].text = col['column_name']
            row_cells[1].text = col['data_type']
            row_cells[2].text = str(col['length']) if col['length'] else '-'
            row_cells[3].text = '是' if col['is_nullable'] else '否'
            row_cells[4].text = col['default_value'] if col['default_value'] else '-'
            row_cells[5].text = col['comment'] if col['comment'] else '-'
        
        # 设置表格列宽
        table.columns[0].width = Inches(1.5)  # 字段名
        table.columns[1].width = Inches(1.2)  # 类型
        table.columns[2].width = Inches(1.0)  # 长度
        table.columns[3].width = Inches(0.8)  # 允许空
        table.columns[4].width = Inches(1.2)  # 默认值
        table.columns[5].width = Inches(2.3)  # 备注
        
        # 添加空行
        self.doc.add_paragraph()

